package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.content.dto.AddCourseDto;
import com.xuecheng.content.dto.CourseBaseInfoDto;
import com.xuecheng.content.dto.EditCourseDto;
import com.xuecheng.content.dto.QueryCourseParamsDto;
import com.xuecheng.content.entity.CourseBase;
import com.xuecheng.content.entity.CourseCategory;
import com.xuecheng.content.entity.CourseMarket;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.dto.PageParamsDto;
import com.xuecheng.dto.PageResult;
import com.xuecheng.exception.XueChengPlusException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @ClassName CourseBaseInfoServiceImpl
 * @Description :课程信息管理接口实现类
 * @Author CG
 * @Date 2023/11/22 11:24
 **/
@Service("CourseBaseInfoService")
@Slf4j
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {


    @Resource
    private CourseBaseMapper courseBaseMapper;

    @Resource
    private CourseMarketMapper courseMarketMapper;

    @Resource
    private CourseCategoryMapper courseCategoryMapper;

    @Override
    public PageResult<CourseBase> queryCourseBaseList(PageParamsDto pageParamsDto, QueryCourseParamsDto queryCourseParamsDto) {


        //拼接查询条件
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //根据名称模糊查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        //根据课程的审核状态 查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());

        //按照课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()),CourseBase::getStatus,queryCourseParamsDto.getPublishStatus());

        //创建分页参数对象
        Page<CourseBase> courseBasePage = new Page<>(pageParamsDto.getPageNo(), pageParamsDto.getPageSize());
        //开始进行分页查询
        Page<CourseBase> courseBasePage1 = courseBaseMapper.selectPage(courseBasePage, queryWrapper);

        //数据列表
        List<CourseBase> records = courseBasePage1.getRecords();
        //总记录数
        long total = courseBasePage1.getTotal();

        PageResult<CourseBase> courseBasePageResult = new PageResult<CourseBase>(records,total,pageParamsDto.getPageNo(), pageParamsDto.getPageSize());

        return courseBasePageResult;

    }

    @Override
    @Transactional//事务控制
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        //参数的合法性校验
        //向课程基本信息course_base表写入数据
        //新增对象
        CourseBase courseBase = new CourseBase();
        //将填写的课程赋值给新对象
        BeanUtils.copyProperties(addCourseDto,courseBase);
        //设置审核状态
        courseBase.setAuditStatus("202002");
        //设置发布状态
        courseBase.setStatus("203001");
        //机构id
        courseBase.setCompanyId(companyId);
        //添加时间
        courseBase.setCreateDate(LocalDateTime.now());

        //添加到数据库表
        int insert = courseBaseMapper.insert(courseBase);
        if(insert<=0){
            //throw new RuntimeException("新增课程信息失败");
            XueChengPlusException.cast("新增课程信息失败");
        }

        //向课程营销表course_market写入数据
        //创建营销表对象
        CourseMarket courseMarket = new CourseMarket();
        //获取课程id
        Long courseId = courseBase.getId();
        //将输入的值赋值给营销信息表对象
        BeanUtils.copyProperties(addCourseDto,courseMarket);
        courseMarket.setId(courseId);

        //保存营销信息
        int i = saveCourseMarket(courseMarket);
        if(i<=0){
            //throw new RuntimeException("营销信息插入失败！");
            XueChengPlusException.cast("营销信息插入失败！");
        }

        //从数据库查询课程的完整的信息(课程信息，营销信息)
        CourseBaseInfoDto courseBaseInfo = getCourseBaseInfo(courseId);
        return courseBaseInfo;
    }




    //保存课程营销表信息
    private int saveCourseMarket(CourseMarket courseMarket){
        //收费规则
        String charge = courseMarket.getCharge();
        if(StringUtils.isBlank(charge)){
            //throw new RuntimeException("没有选择收费规则");
            XueChengPlusException.cast("没有选择收费规则");
        }
        //收费规则为收费
        if(charge.equals("201001")){
            if(courseMarket.getPrice() == null || courseMarket.getPrice().floatValue()<=0){
                //throw new RuntimeException("课程为收费价格不能为空且必须大于0");
                XueChengPlusException.cast("课程为收费价格不能为空且必须大于0");
            }
        }
        //收费规则为不收费
        //根据id从课程营销表查询
        CourseMarket courseMarket1 = courseMarketMapper.selectById(courseMarket.getId());
        //查询存在不存在,添加到数据库
        if(courseMarket1 == null){
            return courseMarketMapper.insert(courseMarket);
        }else{
            //如果已经存在则在数据库进行修改
            BeanUtils.copyProperties(courseMarket,courseMarket1);
            courseMarket1.setId(courseMarket.getId());
            return courseMarketMapper.updateById(courseMarket1);
        }
    }


    //从数据库查询课程的完整的信息(课程信息，营销信息)
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){
        //从课程基本信息表查询
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            return null;
        }
        //从课程营销表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);


        //将课程基本信息表的数据金额课程营销表的数据组装到一起
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);

        //查询分类名称
        CourseCategory courseCategory = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategory.getName());

        return courseBaseInfoDto;
    }

    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //课程Id
        Long courseId = editCourseDto.getId();
        //查询课程信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if(courseBase == null){
            XueChengPlusException.cast("课程不存在");
        }
        //数据合法性校验
        //根据具体业逻辑校验
        //本机构只能修改本机构的课程,不能修改其他机构课程
        if(!companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast("本机构只能修改本机构的课程");
        }

        //封装数据
        BeanUtils.copyProperties(editCourseDto,courseBase);
        //修改时间
        courseBase.setChangeDate(LocalDateTime.now());
        //更新数据库
        int i = courseBaseMapper.updateById(courseBase);
        if(i<=0){
            XueChengPlusException.cast("修改课程失败");
        }
        //更新营销信息
        //根据课程id查询营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        if(courseMarket == null){
            XueChengPlusException.cast("数据库营销信息表不存在,请联系IT维护");
        }
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        int i1 = courseMarketMapper.updateById(courseMarket);
        if(i1<=0){
            XueChengPlusException.cast("修改营销信息失败");
        }
        //查询课程信息
        CourseBaseInfoDto courseBaseInfoDto = getCourseBaseInfo(courseId);
        return courseBaseInfoDto;
    }
}
